package com.example.petchating.android.api

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.aza.deepseektest.retrofit.DeepSeekChatRequest
import com.aza.deepseektest.retrofit.DeepSeekRetrofitClient
import com.aza.deepseektest.retrofit.Message
import com.example.petchating.R
import com.example.petchating.network.ChatService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AndroidChatService(private val context: Context) : ChatService {
    override fun sendMessage(message: String, callback: (String) -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            val systemRole = context.getString(R.string.deepseek_role_system)
            val systemContent = context.getString(R.string.deepseek_content_system)
            val request = DeepSeekChatRequest(
                messages = listOf(
                    Message(systemRole, systemContent),
                    Message("user", message)
                )
            )

            try {
                val response = DeepSeekRetrofitClient.apiService.getChatReply(request)
                val reply = if (response.isSuccessful) {
                    response.body()?.choices?.firstOrNull()?.message?.content ?: "无回复"
                } else {
                    "出错啦：${response.code()}"
                }
                withContext(Dispatchers.Main) {
                    callback(reply)
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    callback("请求失败：${e.message}")
                }
            }
        }
    }
}
